package initialize

import (
	"net/http"
	"server/docs"
	"server/global"
	"server/middleware"
	"server/router"

	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"

	"github.com/gin-gonic/gin"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
)

// InitRouter 初始化路由
func InitRouter() *gin.Engine {
	gin.SetMode(global.Config.System.Env)

	Router := gin.Default()

	// 自定义日志中间件
	//Router.Use(middleware.GinLogger(), middleware.GinRecovery(true))

	// gin 会话路由
	store := cookie.NewStore([]byte(global.Config.System.SessionsSecret))
	Router.Use(sessions.Sessions("session", store))

	// 跨域中间件
	Router.Use(middleware.Cors())

	// 将指定目录下的文件提供给客户端
	// "uploads" 是URL路径前缀，http.Dir("uploads")是实际文件系统中存储文件的目录
	Router.StaticFS(global.Config.Upload.Path, http.Dir(global.Config.Upload.Path))

	// swagger
	docs.SwaggerInfo.BasePath = "/" + global.Config.System.RouterPrefix
	Router.GET(docs.SwaggerInfo.BasePath+"/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
	global.Log.Info("register swagger handler")
	// 创建路由组
	routerGroup := router.RouterGroupApp
	publicGroup := Router.Group(global.Config.System.RouterPrefix)

	// 需要认证
	privateGroup := Router.Group(global.Config.System.RouterPrefix)
	privateGroup.Use(middleware.JWTAuth())
	// 管理员路由
	adminGroup := Router.Group(global.Config.System.RouterPrefix)
	adminGroup.Use(middleware.JWTAuth()).Use(middleware.AdminAuth())
	{
		routerGroup.InitBaseRouter(publicGroup)
	}
	{
		routerGroup.InitUserRouter(privateGroup, publicGroup, adminGroup)
		routerGroup.InitArticleRouter(privateGroup, publicGroup, adminGroup)
	}
	{
		routerGroup.InitImageRouter(adminGroup)
	}
	return Router
}
